import { memo, useEffect, useRef, useState } from 'react'
import './index.scss'

interface propsT{
    url:string;
    duration:number;
}

const MyRecorder = memo(({url,duration}:propsT)=>{
    const [isPlaying, setIsPlaying] = useState(false);
    const audioRef = useRef<HTMLAudioElement>(null);
    const [currentTime,setCurrentTime] = useState<number>(0);
    
    // 播放/暂停切换
    const togglePlay = () => {
        if (audioRef.current) {
            if (isPlaying) {
                audioRef.current.pause();
            } else {
                audioRef.current.play();
            }
            setIsPlaying(!isPlaying);
        }
    };

    function formateTime(time: number){
        const newTime = time/1000
        const minutes = Math.floor(newTime / 60);
        const seconds = Math.floor(newTime % 60);
        return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }

    function handleTimeUpdate(){
        if(!audioRef.current) return
        const time = audioRef.current.currentTime * 1000
        setCurrentTime(time)
        console.log(time);
    }

    function handlePlayEnd(){
        if(!audioRef.current) return
        setIsPlaying(false)
    }

    useEffect(()=>{
        if(audioRef.current){
        }
    },[])
    return (
        <>
            <div className="my_recorder_box">
                <audio 
                    ref={audioRef} 
                    src={url} 
                    onTimeUpdate={handleTimeUpdate}
                    onEnded={handlePlayEnd}
                ></audio>
                <div className="audio-player-container" onClick={togglePlay}>
                    {/* 播放/暂停按钮 */}
                    <div className="play-icon-container">
                        {isPlaying ? (
                        // 暂停图标
                        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <rect x="6" y="5" width="4" height="14" rx="1" fill="currentColor"/>
                            <rect x="14" y="5" width="4" height="14" rx="1" fill="currentColor"/>
                        </svg>
                        ) : (
                        // 播放图标
                        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M8 5V19L19 12L8 5Z" fill="currentColor"/>
                        </svg>
                        )}
                    </div>
                    
                    {/* 时间显示 */}
                    <div className="time-display">
                        <span className="current-time">{formateTime(currentTime)}</span>
                        <div className="time-divider">/</div>
                        <span className="total-time">{formateTime(duration)}</span>
                    </div>
                </div>

            </div>
        </>
    )
})

export default MyRecorder